<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目管理与工时追踪系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            height: 100vh;
            display: flex;
            flex-direction: column;
            background-color: #f5f7fa;
            color: #333;
            overflow: hidden;
        }

        /* 顶部标题栏 */
        .header {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            z-index: 100;
            -webkit-app-region: drag;
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
        }

        .header-actions {
            display: flex;
            gap: 10px;
            -webkit-app-region: no-drag;
        }

        /* 主要内容区域 */
        .main-container {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        /* 左侧项目列表 */
        .project-sidebar {
            width: 300px;
            background-color: white;
            border-right: 1px solid #e1e5e9;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .project-list-header {
            padding: 15px;
            border-bottom: 1px solid #e1e5e9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .project-list {
            flex: 1;
            overflow-y: auto;
            padding: 10px 0;
        }

        .project-item {
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .project-item:hover {
            background-color: #f8f9fa;
        }

        .project-item.active {
            background-color: #e3f2fd;
            border-left: 4px solid #2196f3;
        }

        .project-name {
            font-weight: 600;
            margin-bottom: 5px;
        }

        .project-meta {
            font-size: 12px;
            color: #666;
        }

        /* 右侧项目详情 */
        .project-detail {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            background-color: white;
            margin: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .project-detail-header {
            padding: 20px;
            border-bottom: 1px solid #e1e5e9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .project-info h2 {
            margin-bottom: 5px;
        }

        .project-description {
            color: #666;
            font-size: 14px;
        }

        .work-record-section {
            padding: 20px;
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .work-record-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .work-record-list {
            flex: 1;
            overflow-y: auto;
            border: 1px solid #e1e5e9;
            border-radius: 6px;
            padding: 10px;
        }

        .work-record-item {
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .work-record-item:last-child {
            border-bottom: none;
        }

        .work-record-info h4 {
            margin-bottom: 5px;
        }

        .work-record-meta {
            font-size: 12px;
            color: #666;
        }

        .work-record-actions {
            display: flex;
            gap: 8px;
        }

        /* 表单样式 */
        .form-container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            padding: 20px;
            max-width: 500px;
            margin: 20px auto;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }

        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        textarea.form-control {
            min-height: 80px;
            resize: vertical;
        }

        /* 按钮样式 */
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
        }

        .btn-primary {
            background-color: #2196f3;
            color: white;
        }

        .btn-primary:hover {
            background-color: #0d8bf2;
        }

        .btn-success {
            background-color: #4caf50;
            color: white;
        }

        .btn-success:hover {
            background-color: #45a049;
        }

        .btn-danger {
            background-color: #f44336;
            color: white;
        }

        .btn-danger:hover {
            background-color: #da190b;
        }

        .btn-outline {
            background-color: transparent;
            border: 1px solid #ddd;
        }

        .btn-outline:hover {
            background-color: #f5f5f5;
        }

        .btn-sm {
            padding: 5px 10px;
            font-size: 12px;
        }

        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background-color: white;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #e1e5e9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #e1e5e9;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        /* 工具类 */
        .text-center {
            text-align: center;
        }

        .mt-10 {
            margin-top: 10px;
        }

        .mb-10 {
            margin-bottom: 10px;
        }

        .d-none {
            display: none;
        }

        .d-flex {
            display: flex;
        }

        .flex-column {
            flex-direction: column;
        }

        .justify-content-between {
            justify-content: space-between;
        }

        .align-items-center {
            align-items: center;
        }

        /* 状态指示器 */
        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 5px;
        }

        .status-active {
            background-color: #4caf50;
        }

        .status-completed {
            background-color: #9e9e9e;
        }

        .status-overdue {
            background-color: #f44336;
        }

        /* 统计卡片 */
        .stats-container {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-card {
            flex: 1;
            background: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            text-align: center;
        }

        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #2196f3;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 12px;
            color: #666;
        }

        /* 图表容器 */
        .chart-container {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }

        .chart-placeholder {
            height: 200px;
            background: #f9f9f9;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
        }

        /* 搜索框 */
        .search-box {
            padding: 10px;
            border-bottom: 1px solid #e1e5e9;
        }

        .search-input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        /* 项目标签 */
        .project-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-top: 10px;
        }

        .project-tag {
            background: #e3f2fd;
            color: #1976d2;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 11px;
        }

        /* 消息提示弹窗样式 */
        .msgImg {
            width: 21px;
            height: 21px;
            padding-right: 15px;
        }

        .msgDialog {
            min-width: 360px;
            top: 11%;
            z-index: 2004;
            box-sizing: border-box;
            position: fixed;
            left: 50%;
            transform: translate(-50%, -50%);
            transition: opacity .3s, transform .4s, top .4s, -webkit-transform .4s;
            padding: 15px 15px 15px 20px;
            display: none;
            align-items: center;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .msgSucDialog {
            background-color: #f0f9eb;
            border: 1px solid #e1f3d8;
        }

        .msgWarnDialog {
            background-color: #fdf6ec;
            border: 1px solid #fdf6ec;
        }

        .msgFailDialog {
            background-color: #fef0f0;
            border: 1px solid #fde2e2;
        }

        .msgInfoColor {
            font-weight: 600;
            font-size: 14px;
        }

        .msgInfoSucColor {
            color: #67c23a;
        }

        .msgInfoWarnColor {
            color: #E6A23C;
        }

        .msgInfoFailColor {
            color: #f56c6c;
        }

        .countdown {
            margin-left: 10px;
            font-size: 12px;
            color: #909399;
            font-weight: normal;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .main-container {
                flex-direction: column;
            }

            .msgDialog {
                min-width: 300px;
                left: 50%;
                transform: translateX(-50%);
                top: 20px;
            }

            .project-sidebar {
                width: 100%;
                height: 300px;
            }

            .stats-container {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
<!-- 顶部标题栏 -->
<div class="header">
    <h1>项目管理与工时追踪系统</h1>
    <div class="header-actions">
        <button id="addProjectBtn" class="btn btn-primary">添加项目</button>
        <button id="exportDataBtn" class="btn btn-outline">导出数据</button>
        <button id="importDataBtn" class="btn btn-outline">导入数据</button>
        <button id="showDataPathBtn" class="btn btn-outline">存储路径</button> <!-- 添加这行 -->
    </div>
</div>

<!-- 主要内容区域 -->
<div class="main-container">
    <!-- 左侧项目列表 -->
    <div class="project-sidebar">
        <div class="project-list-header">
            <h3>项目列表</h3>
            <span id="projectCount">0个项目</span>
        </div>
        <div class="search-box">
            <input type="text" id="projectSearch" class="search-input" placeholder="搜索项目...">
        </div>
        <div class="project-list" id="projectList">
            <!-- 项目列表将通过JS动态填充 -->
        </div>
    </div>

    <!-- 右侧项目详情 -->
    <div class="project-detail">
        <div class="project-detail-header">
            <div class="project-info">
                <h2 id="currentProjectName">请选择一个项目</h2>
                <p class="project-description" id="currentProjectDescription">选择左侧项目查看详情</p>
            </div>
            <div class="project-actions">
                <button id="editProjectBtn" class="btn btn-outline d-none">编辑项目</button>
                <button id="addWorkRecordBtn" class="btn btn-primary d-none">添加工时记录</button>
            </div>
        </div>

        <!-- 统计卡片 -->
        <div class="stats-container d-none" id="projectStats">
            <div class="stat-card">
                <div class="stat-value" id="totalWorkHours">0</div>
                <div class="stat-label">总工时</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="totalWorkDays">0</div>
                <div class="stat-label">工作天数</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="avgDailyHours">0</div>
                <div class="stat-label">日均工时</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="projectStatusDisplay">进行中</div>
                <div class="stat-label">项目状态</div>
            </div>
        </div>

        <div class="work-record-section">
            <div class="work-record-header">
                <h3>工时记录</h3>
                <div class="d-flex align-items-center">
                    <span>排序: </span>
                    <select id="sortRecords" class="form-control" style="width: auto; margin-left: 10px;">
                        <option value="date-desc">日期降序</option>
                        <option value="date-asc">日期升序</option>
                        <option value="hours-desc">工时降序</option>
                        <option value="hours-asc">工时升序</option>
                    </select>
                </div>
            </div>
            <div class="work-record-list" id="workRecordList">
                <div class="empty-state">
                    <i>📊📊</i>
                    <p>暂无工时记录</p>
                    <p class="mt-10">选择一个项目并添加工时记录</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑项目模态框 -->
<div id="projectModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="projectModalTitle">添加项目</h3>
            <button id="closeProjectModal" class="btn btn-outline btn-sm">×</button>
        </div>
        <div class="modal-body">
            <form id="projectForm">
                <input type="hidden" id="projectId">
                <div class="form-group">
                    <label for="projectName">项目名称</label>
                    <input type="text" id="projectName" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="projectDescription">项目描述</label>
                    <textarea id="projectDescription" class="form-control"></textarea>
                </div>
                <div class="form-group">
                    <label for="projectStartDate">开始日期</label>
                    <input type="date" id="projectStartDate" class="form-control">
                </div>
                <div class="form-group">
                    <label for="projectEndDate">结束日期</label>
                    <input type="date" id="projectEndDate" class="form-control">
                </div>
                <div class="form-group">
                    <label for="projectStatus">项目状态</label>
                    <select id="projectStatus" class="form-control">
                        <option value="active">进行中</option>
                        <option value="completed">已完成</option>
                        <option value="onHold">暂停</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="projectTags">项目标签 (用逗号分隔)</label>
                    <input type="text" id="projectTags" class="form-control" placeholder="例如: 前端,紧急,客户项目">
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button id="cancelProjectBtn" class="btn btn-outline">取消</button>
            <button id="saveProjectBtn" class="btn btn-primary">保存</button>
        </div>
    </div>
</div>

<!-- 添加工时记录模态框 -->
<div id="workRecordModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="workRecordModalTitle">添加工时记录</h3>
            <button id="closeWorkRecordModal" class="btn btn-outline btn-sm">×</button>
        </div>
        <div class="modal-body">
            <form id="workRecordForm">
                <input type="hidden" id="workRecordId">
                <div class="form-group">
                    <label for="workDate">工作日期</label>
                    <input type="date" id="workDate" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="workHours">工时（小时）</label>
                    <input type="number" id="workHours" class="form-control" min="0.5" step="0.5" required>
                </div>
                <div class="form-group">
                    <label for="workDescription">工作内容</label>
                    <textarea id="workDescription" class="form-control" required></textarea>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button id="cancelWorkRecordBtn" class="btn btn-outline">取消</button>
            <button id="saveWorkRecordBtn" class="btn btn-primary">保存</button>
        </div>
    </div>
</div>
<div id="msg-dialog" class="msgDialog">
    <div id="msgDiv" style="width: 100%; display: flex; align-items: center;"></div>
</div>
<!-- 文件选择器（隐藏） -->
<input type="file" id="fileInput" accept=".json" style="display: none;">

<script>
    // 全局数据
    let projects = [];
    let currentProjectId = null;
    let filteredProjects = [];

    // DOM元素
    const projectList = document.getElementById('projectList');
    const projectCount = document.getElementById('projectCount');
    const currentProjectName = document.getElementById('currentProjectName');
    const currentProjectDescription = document.getElementById('currentProjectDescription');
    const workRecordList = document.getElementById('workRecordList');
    const projectStats = document.getElementById('projectStats');
    const totalWorkHours = document.getElementById('totalWorkHours');
    const totalWorkDays = document.getElementById('totalWorkDays');
    const avgDailyHours = document.getElementById('avgDailyHours');
    const projectStatusDisplay = document.getElementById('projectStatusDisplay');
    const editProjectBtn = document.getElementById('editProjectBtn');
    const addWorkRecordBtn = document.getElementById('addWorkRecordBtn');
    const projectSearch = document.getElementById('projectSearch');
    const sortRecords = document.getElementById('sortRecords');

    // 模态框元素
    const projectModal = document.getElementById('projectModal');
    const workRecordModal = document.getElementById('workRecordModal');
    const projectForm = document.getElementById('projectForm');
    const workRecordForm = document.getElementById('workRecordForm');
    const fileInput = document.getElementById('fileInput');

    // 初始化应用
    document.addEventListener('DOMContentLoaded', function () {
        loadData();
        setupEventListeners();
        renderProjectList();
    });

    // 设置事件监听器
    function setupEventListeners() {
        // 项目相关按钮
        document.getElementById('addProjectBtn').addEventListener('click', showAddProjectModal);
        document.getElementById('editProjectBtn').addEventListener('click', showEditProjectModal);
        document.getElementById('saveProjectBtn').addEventListener('click', saveProject);
        document.getElementById('cancelProjectBtn').addEventListener('click', hideProjectModal);
        document.getElementById('closeProjectModal').addEventListener('click', hideProjectModal);

        // 工时记录相关按钮
        document.getElementById('addWorkRecordBtn').addEventListener('click', showAddWorkRecordModal);
        document.getElementById('saveWorkRecordBtn').addEventListener('click', saveWorkRecord);
        document.getElementById('cancelWorkRecordBtn').addEventListener('click', hideWorkRecordModal);
        document.getElementById('closeWorkRecordModal').addEventListener('click', hideWorkRecordModal);

        // 数据导入导出
        document.getElementById('exportDataBtn').addEventListener('click', exportData);
        document.getElementById('importDataBtn').addEventListener('click', importData);

        // 搜索和排序
        projectSearch.addEventListener('input', filterProjects);
        sortRecords.addEventListener('change', renderProjectDetail);

        // 添加存储路径按钮事件监听器
        document.getElementById('showDataPathBtn').addEventListener('click', showDataPathModal);


        /*     // 模态框外部点击关闭
             projectModal.addEventListener('click', function (e) {
                 if (e.target === projectModal) hideProjectModal();
             });

             workRecordModal.addEventListener('click', function (e) {
                 if (e.target === workRecordModal) hideWorkRecordModal();
             });*/

        document.getElementById('showDataPath').addEventListener('click', async () => {
            const path = await window.electronAPI.getDataPath();
            alert(`数据存储在: ${path}`);
        });

        // 文件选择变化
        fileInput.addEventListener('change', handleFileSelect);
    }

    // 加载数据
    function loadData() {
        // 检查是否在Electron环境中
        if (window.electronAPI) {
            // 在Electron环境中，使用文件系统API
            window.electronAPI.readFile().then(data => {
                if (data && data.length > 0) {
                    projects = data;
                    console.log('从文件加载数据成功');
                } else {
                    projects = getSampleData();
                    console.log('使用示例数据');
                }
                renderProjectList();
            }).catch(error => {
                console.error('加载数据失败:', error);
                projects = getSampleData();
                renderProjectList();
            });
        } else {
            // 在浏览器环境中，使用localStorage
            const savedData = localStorage.getItem('projectData');
            if (savedData) {
                try {
                    projects = JSON.parse(savedData);
                    console.log('从localStorage加载数据成功');
                } catch (e) {
                    console.error('解析本地存储数据失败:', e);
                    projects = getSampleData();
                }
            } else {
                projects = getSampleData();
            }
            renderProjectList();
        }
    }

    // 保存数据
    function saveData() {
        // 检查是否在Electron环境中
        if (window.electronAPI) {
            // 在Electron环境中，使用文件系统API
            window.electronAPI.writeFile(projects).then(result => {
                if (!result.success) {
                    console.error('保存数据失败:', result.error);
                }
            }).catch(error => {
                console.error('保存数据失败:', error);
            });
        } else {
            // 在浏览器环境中，使用localStorage
            localStorage.setItem('projectData', JSON.stringify(projects));
        }
    }

    // 获取示例数据
    function getSampleData() {
        return [
            {
                id: '1',
                name: '示例项目',
                description: '这是一个示例项目，用于演示系统功能',
                startDate: '2023-01-01',
                endDate: '2023-12-31',
                status: 'active',
                tags: ['示例', '演示'],
                workRecords: [
                    {
                        id: '1-1',
                        date: '2023-06-01',
                        hours: 8,
                        description: '项目需求分析和规划',
                        createdAt: '2023-06-01T10:00:00Z'
                    },
                    {
                        id: '1-2',
                        date: '2023-06-02',
                        hours: 6.5,
                        description: '系统架构设计',
                        createdAt: '2023-06-02T09:30:00Z'
                    }
                ],
                createdAt: '2023-01-01T00:00:00Z'
            }
        ];
    }

    // 过滤项目
    function filterProjects() {
        const searchTerm = projectSearch.value.toLowerCase();
        if (searchTerm === '') {
            filteredProjects = [...projects];
        } else {
            filteredProjects = projects.filter(project =>
                project.name.toLowerCase().includes(searchTerm) ||
                (project.description && project.description.toLowerCase().includes(searchTerm)) ||
                (project.tags && project.tags.some(tag => tag.toLowerCase().includes(searchTerm)))
            );
        }
        renderProjectList();
    }

    // 渲染项目列表
    function renderProjectList() {
        projectList.innerHTML = '';
        const projectsToRender = filteredProjects.length > 0 ? filteredProjects : projects;
        projectCount.textContent = `${projectsToRender.length}个项目`;

        if (projectsToRender.length === 0) {
            projectList.innerHTML = `
                    <div class="empty-state">
                        <i>📁📁</i>
                        <p>暂无项目</p>
                        <p class="mt-10">点击"添加项目"创建第一个项目</p>
                    </div>
                `;
            return;
        }

        projectsToRender.forEach(project => {
            const projectItem = document.createElement('div');
            projectItem.className = `project-item ${currentProjectId === project.id ? 'active' : ''}`;

            // 计算项目总工时
            const totalHours = project.workRecords ?
                project.workRecords.reduce((sum, record) => sum + record.hours, 0) : 0;

            // 状态指示器
            let statusClass = 'status-active';
            if (project.status === 'completed') statusClass = 'status-completed';
            if (project.status === 'onHold') statusClass = 'status-overdue';

            projectItem.innerHTML = `
                    <div class="project-name">
                        <span class="status-indicator ${statusClass}"></span>
                        ${project.name}
                    </div>
                    <div class="project-meta">
                        ${project.workRecords ? project.workRecords.length : 0}条工时记录 · ${totalHours.toFixed(1)}小时
                    </div>
                    ${project.tags && project.tags.length > 0 ? `
                        <div class="project-tags">
                            ${project.tags.map(tag => `<span class="project-tag">${tag}</span>`).join('')}
                        </div>
                    ` : ''}
                `;
            projectItem.addEventListener('click', () => selectProject(project.id));
            projectList.appendChild(projectItem);
        });
    }

    // 选择项目
    function selectProject(projectId) {
        currentProjectId = projectId;
        renderProjectList();
        renderProjectDetail();
    }

    // 渲染项目详情
    function renderProjectDetail() {
        const project = projects.find(p => p.id === currentProjectId);

        if (!project) {
            currentProjectName.textContent = '请选择一个项目';
            currentProjectDescription.textContent = '选择左侧项目查看详情';
            editProjectBtn.classList.add('d-none');
            addWorkRecordBtn.classList.add('d-none');
            projectStats.classList.add('d-none');

            workRecordList.innerHTML = `
            <div class="empty-state">
                <i>📊📊</i>
                <p>暂无工时记录</p>
                <p class="mt-10">选择一个项目并添加工时记录</p>
            </div>
        `;
            return;
        }

        // 更新项目信息
        currentProjectName.textContent = project.name;
        currentProjectDescription.textContent = project.description || '暂无描述';

        // 显示操作按钮
        editProjectBtn.classList.remove('d-none');
        addWorkRecordBtn.classList.remove('d-none');
        projectStats.classList.remove('d-none');

        // 更新项目统计
        updateProjectStats(project);


        // 渲染工时记录
        renderWorkRecords(project);
    }

    // 更新项目统计信息
    function updateProjectStats(project) {
        if (!project.workRecords || project.workRecords.length === 0) {
            totalWorkHours.textContent = '0';
            totalWorkDays.textContent = '0';
            avgDailyHours.textContent = '0';
            projectStatusDisplay.textContent = getStatusText(project.status);
            return;
        }

        // 计算总工时
        const totalHours = project.workRecords.reduce((sum, record) => sum + record.hours, 0);
        totalWorkHours.textContent = totalHours.toFixed(1);

        // 计算工作天数
        const uniqueDays = new Set(project.workRecords.map(record => record.date)).size;
        totalWorkDays.textContent = uniqueDays;

        // 计算日均工时
        const avgHours = totalHours / uniqueDays;
        avgDailyHours.textContent = avgHours.toFixed(1);

        // 更新项目状态
        projectStatusDisplay.textContent = getStatusText(project.status);
    }

    // 获取状态文本
    function getStatusText(status) {
        const statusMap = {
            'active': '进行中',
            'completed': '已完成',
            'onHold': '暂停'
        };
        return statusMap[status] || '未知';
    }

    // 渲染工时记录
    function renderWorkRecords(project) {
        workRecordList.innerHTML = '';

        if (!project.workRecords || project.workRecords.length === 0) {
            workRecordList.innerHTML = `
            <div class="empty-state">
                <i>⏱⏱⏱️</i>
                <p>暂无工时记录</p>
                <p class="mt-10">点击"添加工时记录"添加第一条记录</p>
            </div>
        `;
            return;
        }

        // 获取排序方式
        const sortValue = sortRecords.value;
        let sortedRecords = [...project.workRecords];

        // 根据选择排序
        switch (sortValue) {
            case 'date-asc':
                sortedRecords.sort((a, b) => new Date(a.date) - new Date(b.date));
                break;
            case 'date-desc':
                sortedRecords.sort((a, b) => new Date(b.date) - new Date(a.date));
                break;
            case 'hours-asc':
                sortedRecords.sort((a, b) => a.hours - b.hours);
                break;
            case 'hours-desc':
                sortedRecords.sort((a, b) => b.hours - a.hours);
                break;
        }

        sortedRecords.forEach(record => {
            const recordItem = document.createElement('div');
            recordItem.className = 'work-record-item';
            recordItem.innerHTML = `
            <div class="work-record-info">
                <h4>${record.description}</h4>
                <div class="work-record-meta">
                    ${formatDate(record.date)} · ${record.hours}小时
                </div>
            </div>
            <div class="work-record-actions">
                <button class="btn btn-outline btn-sm edit-work-record" data-id="${record.id}">编辑</button>
                <button class="btn btn-outline btn-sm delete-work-record" data-id="${record.id}">删除</button>
            </div>
        `;
            workRecordList.appendChild(recordItem);
        });

        // 添加工时记录的事件监听器
        document.querySelectorAll('.edit-work-record').forEach(btn => {
            btn.addEventListener('click', function () {
                const recordId = this.getAttribute('data-id');
                showEditWorkRecordModal(recordId);
            });
        });

        document.querySelectorAll('.delete-work-record').forEach(btn => {
            btn.addEventListener('click', function () {
                const recordId = this.getAttribute('data-id');
                deleteWorkRecord(recordId);
            });
        });
    }

    // 显示添加项目模态框
    function showAddProjectModal() {
        document.getElementById('projectModalTitle').textContent = '添加项目';
        projectForm.reset();
        document.getElementById('projectId').value = '';
        document.getElementById('projectStartDate').valueAsDate = new Date();
        document.getElementById('projectStatus').value = 'active';
        projectModal.style.display = 'flex';
    }

    // 显示编辑项目模态框
    function showEditProjectModal() {
        const project = projects.find(p => p.id === currentProjectId);
        if (!project) return;

        document.getElementById('projectModalTitle').textContent = '编辑项目';
        document.getElementById('projectId').value = project.id;
        document.getElementById('projectName').value = project.name;
        document.getElementById('projectDescription').value = project.description || '';
        document.getElementById('projectStartDate').value = project.startDate || '';
        document.getElementById('projectEndDate').value = project.endDate || '';
        document.getElementById('projectStatus').value = project.status || 'active';
        document.getElementById('projectTags').value = project.tags ? project.tags.join(',') : '';
        projectModal.style.display = 'flex';
    }

    // 隐藏项目模态框
    function hideProjectModal() {
        projectModal.style.display = 'none';
    }

    // 保存项目
    function saveProject() {
        const projectId = document.getElementById('projectId').value;
        const name = document.getElementById('projectName').value.trim();
        const description = document.getElementById('projectDescription').value.trim();
        const startDate = document.getElementById('projectStartDate').value;
        const endDate = document.getElementById('projectEndDate').value;
        const status = document.getElementById('projectStatus').value;
        const tagsInput = document.getElementById('projectTags').value.trim();
        const tags = tagsInput ? tagsInput.split(',').map(tag => tag.trim()).filter(tag => tag) : [];

        if (!name) {
            showError('请输入项目名称');
            return;
        }

        if (projectId) {
            // 编辑现有项目
            const index = projects.findIndex(p => p.id === projectId);
            if (index !== -1) {
                projects[index] = {
                    ...projects[index],
                    name,
                    description,
                    startDate,
                    endDate,
                    status,
                    tags
                };
            }
        } else {
            // 添加新项目
            const newProject = {
                id: generateId(),
                name,
                description,
                startDate,
                endDate,
                status,
                tags,
                workRecords: [],
                createdAt: new Date().toISOString()
            };
            projects.push(newProject);
            currentProjectId = newProject.id;
        }

        saveData();
        renderProjectList();
        renderProjectDetail();
        hideProjectModal();
    }

    // 显示添加工时记录模态框
    function showAddWorkRecordModal() {
        document.getElementById('workRecordModalTitle').textContent = '添加工时记录';
        workRecordForm.reset();
        document.getElementById('workRecordId').value = '';
        document.getElementById('workDate').valueAsDate = new Date();
        workRecordModal.style.display = 'flex';
    }

    // 显示编辑工时记录模态框
    function showEditWorkRecordModal(recordId) {
        const project = projects.find(p => p.id === currentProjectId);
        if (!project || !project.workRecords) return;

        const record = project.workRecords.find(r => r.id === recordId);
        if (!record) return;

        document.getElementById('workRecordModalTitle').textContent = '编辑工时记录';
        document.getElementById('workRecordId').value = record.id;
        document.getElementById('workDate').value = record.date;
        document.getElementById('workHours').value = record.hours;
        document.getElementById('workDescription').value = record.description;
        workRecordModal.style.display = 'flex';
    }

    // 隐藏工时记录模态框
    function hideWorkRecordModal() {
        workRecordModal.style.display = 'none';
    }

    // 保存工时记录
    function saveWorkRecord() {
        const recordId = document.getElementById('workRecordId').value;
        const date = document.getElementById('workDate').value;
        const hours = parseFloat(document.getElementById('workHours').value);
        const description = document.getElementById('workDescription').value.trim();

        // 验证输入
        if (!date) {
            showError('请选择工作日期', 'workDate');
            return; // 返回false但不关闭模态框
        }

        if (!hours || hours <= 0) {
            showError('请输入有效的工时（大于0）', 'workHours');
            return; // 返回让用户继续编辑
        }

        if (!description) {
            showError('请输入工作内容', 'workDescription');
            return; // 返回让用户继续编辑
        }
        const projectIndex = projects.findIndex(p => p.id === currentProjectId);
        if (projectIndex === -1) return;

        if (!projects[projectIndex].workRecords) {
            projects[projectIndex].workRecords = [];
        }

        if (recordId) {
            // 编辑现有记录
            const recordIndex = projects[projectIndex].workRecords.findIndex(r => r.id === recordId);
            if (recordIndex !== -1) {
                projects[projectIndex].workRecords[recordIndex] = {
                    ...projects[projectIndex].workRecords[recordIndex],
                    date,
                    hours,
                    description
                };
            }
        } else {
            // 添加新记录
            const newRecord = {
                id: generateId(),
                date,
                hours,
                description,
                createdAt: new Date().toISOString()
            };
            projects[projectIndex].workRecords.push(newRecord);
        }

        saveData();
        renderProjectDetail();
        hideWorkRecordModal();
    }

    // 删除工时记录
    function deleteWorkRecord(recordId) {
        if (!confirm('确定要删除这条工时记录吗？')) return;

        const projectIndex = projects.findIndex(p => p.id === currentProjectId);
        if (projectIndex === -1) return;

        projects[projectIndex].workRecords = projects[projectIndex].workRecords.filter(
            r => r.id !== recordId
        );

        saveData();
        renderProjectDetail();
    }

    // 导出数据
    function exportData() {
        const dataStr = JSON.stringify(projects, null, 2);
        const dataBlob = new Blob([dataStr], {type: 'application/json'});

        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `project_data_${new Date().toISOString().split('T')[0]}.json`;
        link.click();
    }

    // 导入数据
    function importData() {
        fileInput.click();
    }

    // 处理文件选择
    function handleFileSelect(event) {
        const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = function (e) {
            try {
                const importedData = JSON.parse(e.target.result);
                if (Array.isArray(importedData)) {
                    projects = importedData;
                    saveData();
                    renderProjectList();
                    currentProjectId = null;
                    renderProjectDetail();
                    alert('数据导入成功！');
                } else {
                    alert('导入的文件格式不正确');
                }
            } catch (error) {
                alert('导入文件失败：' + error.message);
            }
        };
        reader.readAsText(file);

        // 重置文件输入，允许再次选择同一文件
        event.target.value = '';
    }


    // 添加显示数据路径模态框的函数
    function showDataPathModal() {
        // 获取数据路径
        window.electronAPI.getDataPath().then(filePath => {
            // 创建模态框
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.id = 'dataPathModal';
            modal.style.display = 'flex';
            modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>数据存储路径</h3>
                    <button id="closeDataPathModal" class="btn btn-outline btn-sm">×</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>数据文件存储在以下位置：</label>
                        <div style="background: #f5f7fa; padding: 12px; border-radius: 4px; margin-top: 8px; word-break: break-all; font-family: monospace; font-size: 13px;">
                            ${filePath}
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="copyPathBtn" class="btn btn-outline">复制路径</button>
                    <button id="closePathBtn" class="btn btn-primary">确定</button>
                </div>
            </div>
        `;

            document.body.appendChild(modal);

            // 添加事件监听器
            document.getElementById('closeDataPathModal').addEventListener('click', () => {
                document.body.removeChild(modal);
            });

            document.getElementById('closePathBtn').addEventListener('click', () => {
                document.body.removeChild(modal);
            });

            // 复制路径按钮事件
            document.getElementById('copyPathBtn').addEventListener('click', async () => {
                try {
                    await window.electronAPI.copyPathToClipboard(filePath);
                    const copyBtn = document.getElementById('copyPathBtn');
                    const originalText = copyBtn.textContent;
                    copyBtn.textContent = '已复制';
                    copyBtn.classList.remove('btn-outline');
                    copyBtn.classList.add('btn-success');

                    setTimeout(() => {
                        copyBtn.textContent = originalText;
                        copyBtn.classList.remove('btn-success');
                        copyBtn.classList.add('btn-outline');
                    }, 2000);
                } catch (error) {
                    console.error('复制路径失败:', error);
                }
            });


        }).catch(error => {
            console.error('获取数据路径失败:', error);
        });
    }


    // 工具函数：生成唯一ID
    function generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }

    // 工具函数：格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }

    // 显示成功消息
    function showSuccessMessage(message) {
        showMessage(message, 'success');
    }

    // 显示警告消息
    function showWarningMessage(message) {
        showMessage(message, 'warning');
    }

    // 显示错误消息
    function showErrorMessage(message) {
        showMessage(message, 'error');
    }

    // 通用消息显示函数
    function showMessage(message, type) {
        const dialog = document.getElementById('msg-dialog');
        const msgDiv = document.getElementById('msgDiv');

        // 显示弹窗
        dialog.style.display = 'flex';

        // 清除弹窗的样式
        dialog.removeAttribute("class");

        // 设置弹窗样式
        dialog.classList.add('msgDialog');

        // 根据消息类型设置样式
        switch (type) {
            case 'success':
                dialog.classList.add('msgSucDialog');
                break;
            case 'warning':
                dialog.classList.add('msgWarnDialog');
                break;
            case 'error':
                dialog.classList.add('msgFailDialog');
                break;
        }

        // 清空弹窗内容
        msgDiv.innerHTML = '';

        // 根据类型设置图标和颜色
        let iconSvg = '';
        let colorClass = '';

        switch (type) {
            case 'success':
                iconSvg = '<svg class="msgImg" viewBox="0 0 24 24" fill="#67c23a">' +
                    '<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>' +
                    '</svg>';
                colorClass = 'msgInfoSucColor';
                break;
            case 'warning':
                iconSvg = '<svg class="msgImg" viewBox="0 0 24 24" fill="#E6A23C">' +
                    '<path d="M12 5.99L19.53 19H4.47L12 5.99M12 2L1 21h22L12 2zm1 14h-2v2h2v-2zm0-6h-2v4h2v-4z"/>' +
                    '</svg>';
                colorClass = 'msgInfoWarnColor';
                break;
            case 'error':
                iconSvg = '<svg class="msgImg" viewBox="0 0 24 24" fill="#f56c6c">' +
                    '<path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/>' +
                    '</svg>';
                colorClass = 'msgInfoFailColor';
                break;
        }

        // 构建消息内容
        const newsHtml = iconSvg +
            '<span class="msgInfoColor ' + colorClass + '">' + message + '</span>' +
            '<span class="countdown" id="countdown">5s</span>';

        // 将内容添加到页面上
        msgDiv.innerHTML = newsHtml;

        // 启动倒计时
        startCountdown(5);
    }

    // 倒计时函数
    function startCountdown(seconds) {
        let countdownCode = seconds;
        const countdownElement = document.getElementById('countdown');

        // 更新初始显示
        if (countdownElement) {
            countdownElement.textContent = countdownCode + 's';
        }

        // 启动倒计时
        const timer = setInterval(function () {
            countdownCode--;
            if (countdownElement) {
                countdownElement.textContent = countdownCode + 's';
            }

            if (countdownCode <= 0) {
                document.getElementById('msg-dialog').style.display = 'none';
                clearInterval(timer);
            }
        }, 1000);
    }

    // 修改原有的 showError 函数以使用新样式
    function showError(message, focusElementId = null) {
        showErrorMessage(message);

        // 聚焦到指定元素
        if (focusElementId) {
            setTimeout(() => {
                const element = document.getElementById(focusElementId);
                if (element) element.focus();
            }, 100);
        }
    }

    // 模拟Electron API（如果在浏览器中运行）
    if (typeof window.electronAPI === 'undefined') {
        window.electronAPI = {
            readFile: function () {
                return new Promise((resolve) => {
                    const savedData = localStorage.getItem('projectData');
                    if (savedData) {
                        try {
                            resolve(JSON.parse(savedData));
                        } catch (e) {
                            resolve([]);
                        }
                    } else {
                        resolve([]);
                    }
                });
            },
            writeFile: function (data) {
                return new Promise((resolve) => {
                    localStorage.setItem('projectData', JSON.stringify(data));
                    resolve({success: true});
                });
            }
        };
    }
</script>

</body>
</html>